/*
 * main.c
 *
 *  Created on: 23.06.2012
 *      Author: QB60
                q.basic60@gmail.com
 */

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>

typedef
struct
{
  char head[5];
  uint8_t ver;
  uint8_t total_songs;
  uint8_t starting_song;
  uint16_t load_address;
  uint16_t init_address;
  uint16_t play_address;
  char song_name[32];
  char artist_name[32];
  char copyright[32];
  uint16_t NTSC_speed;
  uint8_t bankswitch_info[8];
  uint16_t PAL_speed;
  uint8_t PAL_or_NTSC;
  uint8_t extra_sound_chip;
  uint8_t dummy[4];
} NSF_header;

uint16_t swapWord(uint16_t word)
{
  return (word >> 8) + ((word & 0xFF) << 8);
}

int main(int argc, char *argv[])
{
  if (argc < 2)
  {
    printf("Not enough parameters\n");
    printf("Syntax: NSF_parser input_filename [-f [output_filename]]\n");
    return 0;
  }

  FILE* fi = fopen(argv[1], "rb");
  if (fi == NULL)
  {
    printf("Error! File could not be opened.\n");
    return 0;
  }

  NSF_header header;
  int readed = fread(&header, 1, sizeof(header), fi);
  if (readed != sizeof(header))
  {
    printf("Error reading file.\n");
    return 0;
  }

  printf("Header: %.*s\n", 5, header.head);
  printf("Version: %d\n", header.ver);
  printf("Total songs: %d\n", header.total_songs);
  printf("Starting song: %d\n", header.starting_song);
  printf("Load address: 0x%X\n", header.load_address);
  printf("Init address: 0x%X\n", header.init_address);
  printf("Play address: 0x%X\n", header.play_address);
  printf("Song: %.*s\n", 32, header.song_name);
  printf("Artist: %.*s\n", 32, header.artist_name);
  printf("Copyright: %.*s\n", 32, header.copyright);
  printf("NTSC speed: %d us\n", header.NTSC_speed);
  printf("PAL speed: %d us\n", header.PAL_speed);
  printf("Extra sound byte: %X\n", header.extra_sound_chip);

  int is_bankswitching = 0;
  int i;
  for (i = 0; i < 8; i++)
    if (header.bankswitch_info[i] != 0)
      is_bankswitching = 1;
  printf("NSF %s bankswitching\n", (is_bankswitching == 0) ? "is not use" : "uses");

  if (argc > 2)
  {
    if (stricmp("-f", argv[2]) != 0)
    {
      printf("Error! Wrong parameters.\n");
      return 0;
    }
    else
    {
      char *dot = strpbrk(argv[1], ".\0");
      char new_filename[255];
      strncpy(new_filename, argv[1], dot - argv[1]);
      *(new_filename + (dot - argv[1]))='\0';
      strcat(new_filename, ".bin");

      FILE* fo = fopen((argc == 4) ? argv[3] : new_filename, "wb");
      if (fo == NULL)
      {
        printf("\nError! File could not be created.\n");
        fclose(fi);
        return 0;
      }

      char buffer[255];
      int readed;

      while ((readed = fread(buffer, 1, sizeof(buffer), fi))!=0)
      {
        fwrite(buffer, 1, readed, fo);
      }

      fclose(fo);
    }
  }

  fclose(fi);

  printf("\nOK!");

  return 0;
}
